package parser

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/eval"
	"github.com/ihaiker/tfwrapper/internal/logger"
	"github.com/zclconf/go-cty/cty"
)

func evaluateInputsBlock(options config.Running, file *hcl.File) (map[string]cty.Value, hcl.Diagnostics) {
	log := logger.Logger(options, "inputs")

	content, _, diags := file.Body.PartialContent(&hcl.BodySchema{
		Blocks: []hcl.BlockHeaderSchema{
			{Type: "inputs"},
		},
	})
	if diags.HasErrors() {
		return nil, diags
	}
	if len(content.Blocks) > 1 {
		return nil, hcl.Diagnostics{
			&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "inputs block must be unique",
				Detail:   fmt.Sprintf("inputs block must be unique, but found %d in hclFile %s", len(content.Blocks), options.CurrentConfigPath),
				Context:  &content.Blocks[1].DefRange,
			},
		}
	} else if len(content.Blocks) == 0 {
		return nil, diags
	}
	wec, diags := eval.CreateEvalContext(options)
	if diags.HasErrors() {
		return nil, diags
	}

	inputs, diags := wec.DecodeBlockAttributes(content.Blocks[0])
	for key, _ := range inputs {
		log.Debugf("found defined input %s", color.HiMagentaString(key))
	}
	return inputs, diags
}
